# src/utils/api_key_rotator.py

import os
from typing import Optional, List
from src.utils.logger import get_logger

logger = get_logger(__name__)


class ApiKeyRotator:
    def __init__(self, service_name: str):
        """
        初始化API密钥轮换器
        :param service_name: 服务名称，用于从环境变量中读取对应密钥列表
        """
        self.service_name = service_name.upper()
        self.env_key = f"{self.service_name}_API_KEYS"  # 如 FACEBOOK_API_KEYS
        self.keys = self._load_keys()
        self.current_index = 0

    def _load_keys(self) -> List[str]:
        """从环境变量加载API密钥"""
        keys_str = os.getenv(self.env_key)
        if not keys_str:
            logger.error(f"❌ 环境变量 {self.env_key} 未设置")
            raise EnvironmentError(f"环境变量 {self.env_key} 未设置")

        keys = [key.strip() for key in keys_str.split(",") if key.strip()]
        if not keys:
            logger.error(f"❌ 未找到 {self.service_name} API 密钥")
            raise ValueError(f"未找到 {self.service_name} API 密钥")
        
        return keys

    def get_key(self) -> str:
        """获取下一个可用的API密钥"""
        key = self.keys[self.current_index]
        self.current_index = (self.current_index + 1) % len(self.keys)
        return key